package edu.uwlax.cs.oayonlinestore.client.utils;

import java.util.HashMap;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.HistoryListener;
import com.google.gwt.user.client.ui.SimplePanel;

public abstract class StackPanel extends SimplePanel implements HistoryListener {

	private String currentID = "";

	private StackPage defpage;

	private HashMap panels = new HashMap();

	private StackPage parent;

	public StackPanel(StackPage parent) {
		super();
		this.parent = parent;
		if (parent == null)
			History.addHistoryListener(this);
	}

	public void add(StackPage page) {
		if (panels.get(page.getID()) != null)
			throw new RuntimeException("A Page with the name '" + page.getID()
					+ "' already exists");
		panels.put(page.getID(), page);
		page.setParentPanel(this);
		if (defpage == null)
			defpage = page;
	}

	public String getParentPath() {
		return (parent == null) ? "" : parent.getAnchor();
	}

	public void init() {
		onHistoryChanged(null);
	}

	public void onHistoryChanged(String arg0) {
		String param;
		StackPage page;
		if (arg0 == null || arg0.trim().length() == 0) {
			page = defpage;
			param = null;
			currentID = "";
		} else {
			int i = arg0.indexOf("-");
			currentID = (i < 0) ? arg0 : arg0.substring(0, i);
			param = (i < 0) ? null : arg0.substring(i + 1);
			page = (StackPage) panels.get(currentID);
		}
		if (page == null)
			throw new RuntimeException("Unknown Page:" + arg0);

		page.doInit();
		setWidget(page);
		page.callOnShow(param);
	}
}
